﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QuDao
{
    /// <summary>
    /// LBS地理位置服务工具（统一使用火星坐标系GCJ-02，例如腾讯地图和高德地图都使用该坐标系）
    /// </summary>
    public static class LBSUtils
    {
        /// <summary>
        /// 根据坐标，计算指定范围内的最大最小经纬度
        /// </summary>
        /// <param name="lng">经度</param>
        /// <param name="lat">纬度</param>
        /// <param name="raidus">范围（米）</param>
        /// <returns>返回最大、最小经纬度minLng, minLat, maxLng, maxLat</returns>
        public static Tuple<double,double,double,double> GetAround(double lng, double lat, int raidus)
        {
            double PI = Math.PI; //3.14159265;  //π
            //The circumference of the earth is 24,901 miles.
            //24,901/360 = 69.17 miles / degree  

            double degree = (24901 * 1609) / 360.0;   //地球的周长是24901英里
            double raidusMile = raidus;

            //先计算纬度
            double dpmLat = 1 / degree;
            double radiusLat = dpmLat * raidusMile;
            double minLat = lat - radiusLat;
            double maxLat = lat + radiusLat;

            //计算经度
            double mpdLng = degree * Math.Cos(lat * (PI / 180));  //纬度的余弦
            double dpmLng = 1 / mpdLng;
            double radiusLng = dpmLng * raidusMile;
            double minLng = lng - radiusLng;
            double maxLng = lng + radiusLng;

            //最小经度，最小纬度，最大经度，最大纬度
            //return new double[] { minLng, minLat, maxLng, maxLat };
            return new Tuple<double, double, double, double>(minLng, minLat, maxLng, maxLat);
        }


        /// <summary>
        /// 根据两点间经纬度坐标（double值），计算两点间距离，单位为米
        /// </summary>
        /// <param name="lng1">经度1</param>
        /// <param name="lat1">纬度1</param>
        /// <param name="lng2">经度2</param>
        /// <param name="lat2">纬度2</param>
        /// <returns>返回距离（米）</returns>
        public static double GetDistance(double lng1, double lat1, double lng2, double lat2)
        {
            double EARTH_RADIUS = 6378137;    //地球半径
            double RAD = Math.PI / 180.0;   //   π/180

            double radLat1 = lat1 * RAD;  // // RAD=π/180
            double radLat2 = lat2 * RAD;
            double a = radLat1 - radLat2;
            double b = (lng1 - lng2) * RAD;
            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
             Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s *= EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }

    }
}
